<template>
  <!-- 服务开通弹窗  -->
  <el-dialog class="pick-dialog" :title="ruleForm.isFirst==1?'开通服务':'续费服务'" :visible.sync="dialogVisible" :close-on-click-modal="false" append-to-body :width="ruleForm.isFirst==2?'600px':'1200px'" @close="reset">
    <div class="form-box flex">
      <div class="apiParams_box" v-if="ruleForm.isFirst!=2">
        <el-form ref="form" :model="apiParams" :rules="rules" label-width="100px" style="width: 100%;">
          <el-form-item label="接口渠道" prop="">
            {{ruleForm.businessName}}
          </el-form-item>
          <el-form-item label="渠道联系方式" prop="">
            {{qudaoItem.contact}}
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="apiParams.status" placeholder="请选择状态">
              <el-option v-for="dict in statusList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="价格类型" prop="pricePushType">
            <el-select v-model="apiParams.pricePushType" placeholder="价格类型" clearable>
              <el-option :label="'统一加价'" :value="1" />
              <el-option :label="'原价推送'" :value="2" />
              <el-option :label="'阶梯加价'" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="apiParams.pricePushType==1" label="上调比例(%)" prop="seleep">
            <el-input type="number" style="width:217px" v-model="apiParams.seleep" placeholder="请输入上调比例" />
          </el-form-item>

          <div class="rule-box" v-if="apiParams.pricePushType == 3">
            <!-- <div class="ruletit">
              阶梯加价配置：
            </div> -->
            <div class="tip">
              1、可以设置多个加价规则；每行可以设置xxx~xxx价格的商品,加价百分比和最低加价金额；所有输入框都是必填项。<br />
              2、推送时根据商品金额匹配到加价规则，进行相应的加价。<br />
              3、每行规则含义：符合 最小价格&lt;=商品金额&lt;最大价格 的商品按照该行的规则进行加价。<br />
              4、如果加价百分比为负数，即降价推送，最低加价金额无效。<br />
              5、匹配不到规则的商品，按照原价推送。<br />
            </div>
            <draggable v-model="ruleList" handle=".move" forceFallback="true" group="people" animation="300" @start="onStart" @end="onEnd">
              <transition-group>
                <div class="rule-item flex" v-for="(item,index) in ruleList" :key="index">
                  <!-- <div class="move">
                    <i class="el-icon-sort"></i>
                  </div> -->
                  <div class="flex">
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.minAmount" placeholder="最小价格" style="width:100px" />
                    <span style="margin:0 5px"> - </span>
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.maxAmount" placeholder="最大价格" style="width:100px" />
                    <span>，加价</span>
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.rate" placeholder="" style="width:80px" />
                    <span>%，最低加价</span>
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.zuidiAmount" placeholder="" style="width:100px" />
                    <span>元。</span>
                    <el-button v-if="index!=0" style="margin-left:15px" size="mini" @click="removeRule(index)" icon="el-icon-delete" plain>移除</el-button>
                  </div>
                </div>
              </transition-group>
            </draggable>
            <div style="text-align:right">
              <el-button @click="addRule" plain size="small" type="primary">新增</el-button>
            </div>
          </div>
          <!-- 接口参数 -->
          <div v-if="config&&config.length">
            <el-divider content-position="left">接口参数(请联系对应渠道获取)</el-divider>
            <el-form-item v-for="(attr,i) in config" :key="i" :label="attr.name" :prop="attr.key">
              <el-input type="textarea" style="width:400px" v-model="apiParams[''+attr.key]" :placeholder="'请输入'+attr.name" />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div style="width:100%">
        <el-descriptions :labelStyle="{width:'100px'}" :title="ruleForm.isFirst==1?'开通服务':'续费服务'" border :column='1'>
          <el-descriptions-item label="服务名称">接口渠道：{{ruleForm.businessName}}</el-descriptions-item>
          <!-- <el-descriptions-item label="渠道联系方式">{{qudaoItem.contact}}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="可对接游戏">{{ruleForm.gameNames}}</el-descriptions-item> -->
          <el-descriptions-item :label="ruleForm.isFirst==1?'开通时长':'续费时长'">
            <div>
              <span v-if="qudaoItem.buyWay==1">免费开通</span>
              <span v-if="userInfo.userId!=1&&qudaoItem.buyWay==2">{{qudaoItem.minMonthDuration}}个月（{{ruleForm.isFirst==1?'首次开通':'手动续费'}}默认{{qudaoItem.minMonthDuration}}个月，自动续费每次1个月）</span>
              <span v-if="qudaoItem.buyWay==3">长期开通</span>
              <span v-if="userInfo.userId==1&&qudaoItem.buyWay==2">
                <el-input-number @change="monthChange" style="width:130px" v-model="ruleForm.openMonth" :min="1" :max="100" label="label"></el-input-number>月
              </span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="所需虞豆">
            <div>
              <span v-if="userInfo.userId!=1">{{ruleForm.cost}}</span>
              <el-input v-else type="number" style="width:130px" v-model="ruleForm.cost" :min="0" :max="100" label="label"></el-input>
              <span>（{{qudaoItem.monthAmount}}虞豆/月）</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="当前虞豆">
            {{campNumber}}
          </el-descriptions-item>
          <el-descriptions-item label="自动续费">
            <el-switch v-model="ruleForm.isAuto" :active-value="1" :inactive-value="2" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </el-descriptions-item>
        </el-descriptions>
        <div class="center">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">
            <span v-if="ruleForm.isFirst==1">确认开通</span>
            <span v-else>确认续费</span>
          </el-button>
        </div>
      </div>
    </div>
    <chongzhi ref="chongzhi"></chongzhi>
  </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import valueAddedServices from "@/api/shanghuduan/valueAddedServices";
import { getShopDetail } from "@/api/system/shopManage";
import chongzhi from "@/views/tenantPages/moneys/components/chongzhijifen.vue";
//导入draggable组件
import draggable from "vuedraggable";
export default {
  name: "",
  props: ["tenantId", "campNumber"],
  components: { chongzhi, draggable },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      type: "",
      ruleForm: {
        type: "2",
        businessId: "",
        businessName: "",
        openMonth: "",
        isAuto: "",
        cost: "",
        isFirst: 1,
      },
      apiParams: {
        status: "1",
        tenantId: "",
        merchantUserId: "",
        merchantUserName: "",
        saleName: "",
        name: "",
        interfaceUserName: "",
        interfaceUserId: "",
        seleep: "",
        pricePushType: "",
      },
      rules: {
        pricePushType: [
          { required: true, message: "请选择价格类型", trigger: "change" },
        ],
      },
      statusList: [
        {
          id: "1",
          name: "可用",
        },
        {
          id: "2",
          name: "禁用",
        },
      ],
      config: [], //接口参数配置的字段
      // from: "", //来源
      // activeInfo:'',
      // monthList:[],
      // activeIndex:0,
      qudaoItem: {},
      tenantInfo: "", //当前租户信息
      ruleList: [
        {
          minAmount: 0,
          maxAmount: "",
          sort: 0,
          zuidiAmount: "",
          rate: "",
        },
      ],
      drag: false,
    };
  },
  created() {},
  methods: {
    open(item, isFirst) {
      this.qudaoItem = { ...item };
      this.ruleList = [
        {
          minAmount: 0,
          maxAmount: "",
          sort: 0,
          zuidiAmount: "",
          rate: "",
        },
      ];
      this.loading = false;
      let costNum = 0;
      if (this.qudaoItem.buyWay == 2) {
        costNum = this.qudaoItem.minMonthDuration * this.qudaoItem.monthAmount;
      } else if (this.qudaoItem.buyWay == 3) {
        costNum = this.qudaoItem.monthAmount;
      }
      this.ruleForm = {
        type: 2,
        businessId:this.qudaoItem.businessId||this.qudaoItem.id ,
        businessName: this.qudaoItem.name,
        openMonth:
          this.qudaoItem.buyWay == 2 ? this.qudaoItem.minMonthDuration : "",
        isAuto: 1,
        autoMonth: 1,
        cost: costNum,
        isFirst: isFirst,
      };
      if (this.ruleForm.isFirst == 2) {
        this.ruleForm.valueAddedServiceId = this.qudaoItem.id;
        this.apiParams = {};
      }

      this.getShopInfo();
    },
    // 月数改变
    monthChange(e) {
      this.qudaoItem.openMonth = e;
      this.ruleForm.cost =
        this.qudaoItem.openMonth * this.qudaoItem.monthAmount;
    },
    // 获取租户店铺信息
    async getShopInfo() {
      // if(this.ruleForm.isFirst==2){
      //   return
      // }
      const { data } = await getShopDetail(this.tenantId);
      this.tenantInfo = data;
      this.interfaceUserIdChange();
    },
    // 组装api开通需要的初始数据
    interfaceUserIdChange() {
      if (this.qudaoItem.code) {
        this.apiParams.tenantId = this.tenantInfo.tenantId;
        this.apiParams.merchantUserId = this.tenantInfo.tenantId;
        this.apiParams.merchantUserName = this.tenantInfo.tenantName;

        this.apiParams.saleName =
          this.tenantInfo.tenantId + "_" + this.qudaoItem.code;
        this.apiParams.name =
          this.tenantInfo.tenantName + "_" + this.qudaoItem.name;

        this.apiParams.interfaceUserName = this.qudaoItem.name;
        this.apiParams.interfaceUserId = this.qudaoItem.businessId||this.qudaoItem.id;
      } else {
        this.apiParams.interfaceUserName = "";
        this.apiParams.interfaceUserId = "";
        this.apiParams.saleName = "";
        this.apiParams.name = "";
        return this.$alert("该接口渠道配置有误，请联系管理员处理。");
      }
      this.config = JSON.parse(this.qudaoItem.configTemplate);
      let obj = {};
      if (this.config && this.config.length) {
        for (let i = 0; i < this.config.length; i++) {
          let attr = this.config[i];
          if (!attr.isShow) {
            this.config.splice(i, 1);
            i--;
            continue;
          } else if (attr.isShow && attr.isMust) {
            this.rules[attr.key] = [
              {
                required: true,
                message: "请输入" + attr.name,
                trigger: "blur",
              },
            ];
          } else {
            if (this.rules[attr.key]) delete this.rules[attr.key];
          }
          obj[attr.key] = "";
        }
        this.apiParams = { ...this.apiParams, ...obj };
      }
      this.dialogVisible = true;
    },
    submitForm() {
      if (this.ruleForm.isFirst == 2) {
        this.submitFormSure();
      } else {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.ruleForm.salePartner = { ...this.apiParams };
            this.submitFormSure();
          }
        });
      }
    },
    submitFormSure() {
      if (!(this.apiParams.pricePushType != 3||(this.apiParams.pricePushType == 3&&this.validateRule()))) {
        return this.$alert("阶梯加价参数请填写完整！");
      }
      // 处理填写的参数，去掉前后空格和换行
      if (this.config && this.config.length){
        for (let i = 0; i < this.config.length; i++) {
          let attr = this.config[i];
          if(this.ruleForm[attr.key]) this.ruleForm[attr.key] = this.ruleForm[attr.key].trim()
        }
      }
      const loading = this.$loading();
      this.ruleForm.tenantId = this.tenantId;
      valueAddedServices
        .openValueAddedServices(this.ruleForm)
        .then((res) => {
          loading.close();
          this.$store.dispatch("GetInfo");
          this.$emit("success");
          if (res.code == 200) {
            this.$alert("操作成功！")
            // this.$message.success("操作成功！");
            if (this.ruleForm.isFirst != 2) {
              this.$confirm(
                "操作成功！新开通接口渠道需要在接口管理进行推送配置",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "",
                }
              )
                .then(() => {
                  // this.$router.push({
                  //   path: "/tenantUtils/partner/index",
                  // });
                })
                .catch(() => {});
            }
          }
          this.close();
        })
        .catch((err) => {
          loading.close();
          this.chongzhijifen();
        });
    },
    // 阶梯加价相关
    //开始拖拽事件
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false;
      this.ruleList.forEach((r, i) => {
        r.sort = i;
      });
    },
    inputChange() {
      this.setRuleStr();
      // this.$refs..resetFields()
      // this.$refs.form2.validate(valid=>{})
    },
    // 添加一条规则
    addRule() {
      let lth = this.ruleList.length;
      this.ruleList.push({
        minAmount: lth > 0 ? this.ruleList[lth - 1].maxAmount : "",
        maxAmount: "",
        sort: 999,
        zuidiAmount: "",
        rate: "",
      });
    },
    //移除一条规则
    removeRule(index) {
      this.ruleList.splice(index, 1);
      this.setRuleStr();
    },
    validateRule() {
      let pass = true;
      if (this.ruleList && this.ruleList.length) {
        this.ruleList.forEach((r) => {
          if (
            !(r.minAmount || r.minAmount == 0) ||
            !r.maxAmount ||
            !r.zuidiAmount ||
            !r.rate
          ) {
            pass = false;
          }
        });
      } else {
        pass = false;
      }
      return pass;
    },
    // 处理规则字符串
    setRuleStr() {
      this.ruleList.forEach((r, i) => {
        r.sort = i;
      });
      this.apiParams.rule = JSON.stringify(this.ruleList);
    },

    // 阶梯加价结束
    // 点击充值
    chongzhijifen() {
      this.$refs.chongzhi.open();
      // this.$refs.paySuccess.open();
    },
    close(formName) {
      this.$emit("close");
      this.dialogVisible = false;
    },
    reset() {
      this.$refs["form"] && this.$refs["form"].resetFields();
    },
  },
};
</script>
<style scoped lang="scss">
.kuaijie {
  flex-wrap: wrap;
}
.kuaijie-item {
  min-width: 150px;
  // width: 100%;
  // height: 49px;
  border-radius: 4px;
  border: 1px solid $yellow;
  text-align: center;
  color: $yellow;
  padding: 10px;
  margin-right: 30px;
  margin-bottom: 10px;
  cursor: pointer;
  position: relative;
  &.active {
    color: #fff;
    background-color: #ff9717;
  }
  .xs {
    background-color: #eb8200;
    width: 33px;
    height: 17px;
    font-size: 12px;
    line-height: 16px;
    position: absolute;
    top: 0;
    right: 0;
    color: #fff;
  }
}
.center {
  text-align: center;
  margin-top: 15px;
}
.apiParams_box {
  width: 60%;
  flex-shrink: 0;
  margin-right: 15px;

  .rule-item ::v-deep{
    .el-input{
      width: 100px;
    }
  }
}

.rule-box {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  .ruletit {
    font-size: 18px;
    font-weight: 601;
  }
  .tip {
    color: red;
  }
}
.rule-item {
  /* margin-bottom: 20px; */
  border-bottom: 1px solid #ccc;
  padding: 10px;
  align-items: center;
  > .flex {
    align-items: center;
  }
}
.rule-item:last-of-type {
  border: none;
}
.rule-item .move {
  text-align: center;
  width: 30px;
  height: 30px;
  line-height: 30px;
  cursor: pointer;
  background-color: #46a6ff;
  color: #fff;
  font-size: 20px;
  border-radius: 50%;
  margin-right: 10px;
}
</style>
